package com.minxyz.mynative.controller;

import com.minxyz.mynative.entity.RequestLog;
import com.minxyz.mynative.repository.RequestLogRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Enumeration;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/")
public class RequestLogController {

    @Autowired
    private RequestLogRepository requestLogRepository;

    @GetMapping("/log")
    public String log(HttpServletRequest request) {
        RequestLog entity = new RequestLog();
        entity.setId(UUID.randomUUID().toString().toUpperCase());
        Enumeration<String> names = request.getHeaderNames();
        StringBuilder builder = new StringBuilder(request.getRequestURL()).append("\r\n");
        while (names.hasMoreElements()) {
            String name = names.nextElement();
            builder.append(name).append(" = ").append(request.getHeader(name)).append("\r\n");
        }
        entity.setContent(builder.toString());
        entity.setLogDate(new Date());
        requestLogRepository.save(entity);
        return HttpStatus.OK.toString();
    }

}
